<template>
  <div class="billing-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>计费管理</span>
          <el-button type="primary" @click="showGenerateBillDialog">
            生成账单
          </el-button>
        </div>
      </template>

      <!-- 查询条件 -->
      <el-form :model="queryForm" :inline="true" class="query-form">
        <el-form-item label="客户">
          <el-select v-model="queryForm.customerId" placeholder="选择客户" clearable>
            <el-option
              v-for="customer in customers"
              :key="customer.id"
              :label="customer.name"
              :value="customer.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计费周期">
          <el-date-picker
            v-model="queryForm.billingPeriod"
            type="month"
            placeholder="选择计费周期"
            format="YYYY-MM"
            value-format="YYYY-MM"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadBillingData">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 设备计费汇总表格 -->
      <el-table :data="billingData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="deviceId" label="设备ID" width="80" />
        <el-table-column prop="serialNo" label="设备序列号" width="150" />
        <el-table-column prop="model" label="设备型号" width="120" />
        <el-table-column prop="areaName" label="所属区域" width="120" />
        <el-table-column prop="siteName" label="所属站点" width="120" />
        <el-table-column prop="customerName" label="客户" width="120" />
        <el-table-column prop="currentMeterReading" label="当前读数" width="100" />
        <el-table-column prop="lastMeterReading" label="上次读数" width="100" />
        <el-table-column prop="usageAmount" label="用水量(吨)" width="100" />
        <el-table-column prop="waterPrice" label="单价(元/吨)" width="100" />
        <el-table-column label="预估费用(元)" width="120">
          <template #default="{ row }">
            {{ ((row.usageAmount || 0) * (row.waterPrice || 0)).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="billingPeriod" label="计费周期" width="100" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="updateMeterReading(row)">
              更新读数
            </el-button>
            <el-button size="small" @click="updateWaterPrice(row)">
              设置单价
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 生成账单对话框 -->
    <el-dialog v-model="generateBillDialogVisible" title="生成账单" width="500px">
      <el-form :model="generateBillForm" :rules="generateBillRules" ref="generateBillFormRef">
        <el-form-item label="客户" prop="customerId">
          <el-select v-model="generateBillForm.customerId" placeholder="选择客户">
            <el-option
              v-for="customer in customers"
              :key="customer.id"
              :label="customer.name"
              :value="customer.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计费周期" prop="billingPeriod">
          <el-date-picker
            v-model="generateBillForm.billingPeriod"
            type="month"
            placeholder="选择计费周期"
            format="YYYY-MM"
            value-format="YYYY-MM"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="generateBillDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="generateBill" :loading="generating">
          生成账单
        </el-button>
      </template>
    </el-dialog>

    <!-- 更新抄表读数对话框 -->
    <el-dialog v-model="meterReadingDialogVisible" title="更新抄表读数" width="400px">
      <el-form :model="meterReadingForm" :rules="meterReadingRules" ref="meterReadingFormRef">
        <el-form-item label="设备序列号">
          <span>{{ selectedDevice?.serialNo }}</span>
        </el-form-item>
        <el-form-item label="当前读数" prop="currentReading">
          <el-input-number
            v-model="meterReadingForm.currentReading"
            :min="0"
            :precision="2"
            placeholder="请输入当前抄表读数"
          />
        </el-form-item>
        <el-form-item label="计费周期" prop="billingPeriod">
          <el-date-picker
            v-model="meterReadingForm.billingPeriod"
            type="month"
            placeholder="选择计费周期"
            format="YYYY-MM"
            value-format="YYYY-MM"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="meterReadingDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitMeterReading" :loading="updating">
          更新读数
        </el-button>
      </template>
    </el-dialog>

    <!-- 更新水费单价对话框 -->
    <el-dialog v-model="waterPriceDialogVisible" title="设置水费单价" width="400px">
      <el-form :model="waterPriceForm" :rules="waterPriceRules" ref="waterPriceFormRef">
        <el-form-item label="区域名称">
          <span>{{ selectedArea?.name }}</span>
        </el-form-item>
        <el-form-item label="水费单价(元/吨)" prop="waterPrice">
          <el-input-number
            v-model="waterPriceForm.waterPrice"
            :min="0"
            :precision="2"
            placeholder="请输入水费单价"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="waterPriceDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitWaterPrice" :loading="updating">
          设置单价
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { BillingAPI } from '@/api/system/billing.api'
import CustomerAPI from '@/api/system/customer.api'

// 响应式数据
const queryForm = reactive({
  customerId: null,
  billingPeriod: null
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const billingData = ref([])
const customers = ref([])
const generating = ref(false)
const updating = ref(false)
const loading = ref(false)

// 对话框相关
const generateBillDialogVisible = ref(false)
const meterReadingDialogVisible = ref(false)
const waterPriceDialogVisible = ref(false)

const generateBillForm = reactive({
  customerId: null,
  billingPeriod: null
})

const meterReadingForm = reactive({
  currentReading: null,
  billingPeriod: null
})

const waterPriceForm = reactive({
  waterPrice: null
})

const selectedDevice = ref(null)
const selectedArea = ref(null)

// 表单验证规则
const generateBillRules = {
  customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
  billingPeriod: [{ required: true, message: '请选择计费周期', trigger: 'change' }]
}

const meterReadingRules = {
  currentReading: [{ required: true, message: '请输入当前抄表读数', trigger: 'blur' }],
  billingPeriod: [{ required: true, message: '请选择计费周期', trigger: 'change' }]
}

const waterPriceRules = {
  waterPrice: [{ required: true, message: '请输入水费单价', trigger: 'blur' }]
}

const generateBillFormRef = ref()
const meterReadingFormRef = ref()
const waterPriceFormRef = ref()

// 方法
const loadCustomers = async () => {
  try {
    const response = await CustomerAPI.getCustomerList()
    customers.value = response || []
  } catch (error) {
    console.error('加载客户列表失败:', error)
    ElMessage.error('加载客户列表失败')
  }
}

const loadBillingData = async () => {
  try {
    loading.value = true
    
    const params = {
      ...queryForm,
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    
    const response = await BillingAPI.getDeviceBillingSummary(params)
    
    // 由于request.js的响应拦截器已经返回了data部分，所以response直接就是后端返回的result对象
    if (response) {
      billingData.value = response.records || []
      pagination.total = response.total || 0
      console.log('计费数据加载成功:', response)
    } else {
      ElMessage.error('获取数据失败')
    }
  } catch (error) {
    console.error('加载计费数据失败:', error)
    ElMessage.error('加载计费数据失败')
  } finally {
    loading.value = false
  }
}

const resetQuery = () => {
  Object.assign(queryForm, {
    customerId: null,
    billingPeriod: null
  })
  pagination.currentPage = 1
  loadBillingData()
}

const showGenerateBillDialog = () => {
  generateBillForm.customerId = null
  generateBillForm.billingPeriod = null
  generateBillDialogVisible.value = true
}

const generateBill = async () => {
  try {
    await generateBillFormRef.value.validate()
    
    generating.value = true
    await BillingAPI.generateBillFromDevices(generateBillForm)
    
    ElMessage.success('账单生成成功')
    generateBillDialogVisible.value = false
    loadBillingData()
  } catch (error) {
    console.error('生成账单失败:', error)
    ElMessage.error('生成账单失败')
  } finally {
    generating.value = false
  }
}

const updateMeterReading = (row) => {
  selectedDevice.value = row
  meterReadingForm.currentReading = row.currentMeterReading
  meterReadingForm.billingPeriod = row.billingPeriod
  meterReadingDialogVisible.value = true
}

const submitMeterReading = async () => {
  try {
    await meterReadingFormRef.value.validate()
    
    updating.value = true
    await BillingAPI.updateDeviceMeterReading(
      selectedDevice.value.id,
      meterReadingForm.currentReading,
      meterReadingForm.billingPeriod
    )
    
    ElMessage.success('抄表读数更新成功')
    meterReadingDialogVisible.value = false
    loadBillingData()
  } catch (error) {
    console.error('更新抄表读数失败:', error)
    ElMessage.error('更新失败')
  } finally {
    updating.value = false
  }
}

const updateWaterPrice = (row) => {
  selectedArea.value = { id: row.areaId, name: row.areaName }
  waterPriceForm.waterPrice = row.waterPrice
  waterPriceDialogVisible.value = true
}

const submitWaterPrice = async () => {
  try {
    await waterPriceFormRef.value.validate()
    
    updating.value = true
    await BillingAPI.updateAreaWaterPrice(
      selectedArea.value.id,
      waterPriceForm.waterPrice
    )
    
    ElMessage.success('水费单价设置成功')
    waterPriceDialogVisible.value = false
    loadBillingData()
  } catch (error) {
    console.error('设置水费单价失败:', error)
    ElMessage.error('设置失败')
  } finally {
    updating.value = false
  }
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadBillingData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadBillingData()
}

// 生命周期
onMounted(() => {
  loadCustomers()
  loadBillingData()
})
</script>

<style scoped>
.billing-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.query-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 